import axios from "axios";
import { showFailToast } from "vant";
import "vant/es/toast/style";
import store from "@/store";

// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 30000,
});

service.interceptors.request.use(
  (config) => {
    let token;
    if (import.meta.env.MODE === "development") {
      token = import.meta.env.VITE_MOCK_TOKEN; // 开发环境使用 mock token
    } else {
      token = store.state.token; // 生产环境使用真实 token
    }

    if (token) {
      config.headers.Authorization = `${token}`; // 添加 Authorization 到请求头
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    const { code, data, message } = res.data;
    if (code == 200 || code == 0) {
      return data;
    } else {
      showFailToast(message);
      return Promise.reject(message);
    }
  },
  (error) => {
    showFailToast(error);
    return Promise.reject(error);
  }
);
export default service;
